import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, FormArray, Validators } from '@angular/forms';
import { ActivatedRoute, Router } from '@angular/router';
import { AdminService, ProblemCreateRequest, ProblemDTO, TestCase } from '../../services/admin.service';

@Component({
  standalone: false,
  selector: 'app-problem-form',
  templateUrl: './problem-form.component.html',
  styleUrls: ['./problem-form.component.css']
})
export class ProblemFormComponent implements OnInit {
  problemForm: FormGroup;
  isEditMode = false;
  problemId: number | null = null;
  loading = false;
  saving = false;
  error: string | null = null;

  difficulties = ['Easy', 'Medium', 'Hard'];

  constructor(
    private fb: FormBuilder,
    private adminService: AdminService,
    private route: ActivatedRoute,
    private router: Router
  ) {
    this.problemForm = this.createForm();
  }

  ngOnInit(): void {
    this.route.params.subscribe(params => {
      if (params['id']) {
        this.isEditMode = true;
        this.problemId = +params['id'];
        this.loadProblem();
      } else {
        // 如果是创建模式，添加一个默认的测试用例
        this.addTestCase();
      }
    });
  }

  createForm(): FormGroup {
    return this.fb.group({
      title: ['', [Validators.required, Validators.minLength(1)]],
      description: ['', [Validators.required, Validators.minLength(10)]],
      difficulty: ['Easy', Validators.required],
      timeLimit: [1000, [Validators.required, Validators.min(100), Validators.max(10000)]],
      memoryLimit: [128, [Validators.required, Validators.min(16), Validators.max(1024)]],
      testCases: this.fb.array([])
    });
  }

  get testCases(): FormArray {
    return this.problemForm.get('testCases') as FormArray;
  }

  createTestCaseForm(testCase?: TestCase): FormGroup {
    return this.fb.group({
      input: [testCase?.input || '', Validators.required],
      expectedOutput: [testCase?.expectedOutput || '', Validators.required],
      isSample: [testCase?.isSample || false]
    });
  }

  addTestCase(): void {
    this.testCases.push(this.createTestCaseForm());
  }

  removeTestCase(index: number): void {
    if (this.testCases.length > 1) {
      this.testCases.removeAt(index);
    }
  }

  loadProblem(): void {
    if (!this.problemId) return;

    this.loading = true;
    this.error = null;

    this.adminService.getProblem(this.problemId).subscribe({
      next: (response) => {
        if (response.success && response.data) {
          this.populateForm(response.data);
        } else {
          this.error = response.message || '加载题目失败';
        }
        this.loading = false;
      },
      error: (error) => {
        this.error = '网络错误，请稍后重试';
        this.loading = false;
        console.error('Error loading problem:', error);
      }
    });
  }

  populateForm(problem: ProblemDTO): void {
    this.problemForm.patchValue({
      title: problem.title,
      description: problem.description,
      difficulty: problem.difficulty,
      timeLimit: problem.timeLimit,
      memoryLimit: problem.memoryLimit
    });

    // 清空现有测试用例
    while (this.testCases.length !== 0) {
      this.testCases.removeAt(0);
    }

    // 添加题目的测试用例
    if (problem.testCases && problem.testCases.length > 0) {
      problem.testCases.forEach(testCase => {
        this.testCases.push(this.createTestCaseForm(testCase));
      });
    } else {
      // 如果没有测试用例，添加一个空的
      this.addTestCase();
    }
  }

  onSubmit(): void {
    if (this.problemForm.invalid) {
      this.markFormGroupTouched(this.problemForm);
      return;
    }

    this.saving = true;
    this.error = null;

    const formValue = this.problemForm.value;
    const problemData: ProblemCreateRequest = {
      title: formValue.title,
      description: formValue.description,
      difficulty: formValue.difficulty,
      timeLimit: formValue.timeLimit,
      memoryLimit: formValue.memoryLimit,
      testCases: formValue.testCases
    };

    const operation = this.isEditMode && this.problemId
      ? this.adminService.updateProblem(this.problemId, problemData)
      : this.adminService.createProblem(problemData);

    operation.subscribe({
      next: (response) => {
        if (response.success) {
          this.router.navigate(['/admin']);
        } else {
          this.error = response.message || '保存失败';
        }
        this.saving = false;
      },
      error: (error) => {
        this.error = '网络错误，请稍后重试';
        this.saving = false;
        console.error('Error saving problem:', error);
      }
    });
  }

  cancel(): void {
    this.router.navigate(['/admin']);
  }

  private markFormGroupTouched(formGroup: FormGroup): void {
    Object.keys(formGroup.controls).forEach(key => {
      const control = formGroup.get(key);
      control?.markAsTouched();

      if (control instanceof FormGroup) {
        this.markFormGroupTouched(control);
      } else if (control instanceof FormArray) {
        control.controls.forEach(arrayControl => {
          if (arrayControl instanceof FormGroup) {
            this.markFormGroupTouched(arrayControl);
          }
        });
      }
    });
  }

  getFieldError(fieldName: string): string | null {
    const field = this.problemForm.get(fieldName);
    if (field && field.invalid && field.touched) {
      if (field.errors?.['required']) {
        return '此字段为必填项';
      }
      if (field.errors?.['minlength']) {
        return `最少需要 ${field.errors['minlength'].requiredLength} 个字符`;
      }
      if (field.errors?.['min']) {
        return `最小值为 ${field.errors['min'].min}`;
      }
      if (field.errors?.['max']) {
        return `最大值为 ${field.errors['max'].max}`;
      }
    }
    return null;
  }

  getTestCaseError(index: number, fieldName: string): string | null {
    const testCase = this.testCases.at(index);
    const field = testCase.get(fieldName);
    if (field && field.invalid && field.touched) {
      if (field.errors?.['required']) {
        return '此字段为必填项';
      }
    }
    return null;
  }
}